<?php

require_once 'core.php';
require_once cf\Config::path.'shop.php';

$tpl = 'edit_product';

function do_edit_save($aid, $params) {
	$pid = cf\api\admin\doAction($aid, $params);
	if (array_key_exists('id',$params)) {
		$pid = $params['id'];
	}
	
			//update categories
	$pos = cf\query2arrays('SELECT group_id,sort_order FROM cf_products_in_groups WHERE product_id=:id',array('id'=>$pid),false,'group_id');
	cf\execQuery('DELETE FROM cf_products_in_groups WHERE product_id=:id',array('id'=>$pid));
	$categories = cf\param::exist('category') ? cf\param::get('category') : array();
	$q = cf\createQuery('INSERT INTO cf_products_in_groups (group_id,product_id,sort_order) VALUES(:groupId,:productId,:sortOrder)',array('productId'=>$pid));
	foreach ($categories as $catId) {
		$q->setParam('groupId',$catId);
		$q->setParam('sortOrder', array_key_exists($catId,$pos) ? $pos[$catId]['sort_order'] : 500);
		$q->execute();
	}
	
			//update attributes
	if (cf\param::exist('attributes')) {
		$attrValues = cf\param::get('attributes');
		$attributes = new cf\ProductAttributes($pid, true);
		foreach ($attributes as $attr) {
			if (array_key_exists($attr->id(), $attrValues)) {
				$attr->setValue($attrValues[$attr->id()]);
			}
		}
		$product = new cf\Product($pid);
		$product->setAttributes($attributes);
	}	
}

require_once 'edit.php';
?>